package cn.darksoul3.springcloud.conrroller;

import cn.darksoul3.common.result.GlobalCodeMsgEnum;
import cn.darksoul3.common.result.ObjectResult;
import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@Slf4j
@RefreshScope
@RestController
public class tick {

    @Value(value = "${server.port}")
    private String port;

    private final RestTemplate rest;

    @Autowired
    public tick(RestTemplate rest) {
        this.rest = rest;
    }

    @GetMapping(value = "/tick")
    public ObjectResult tick() {
        log.info("this is tick");
        return ObjectResult.succeed(this.port);
    }

    @HystrixCommand(fallbackMethod = "handleTout", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    @GetMapping(value = "/tout")
    public ObjectResult tout() throws InterruptedException {
        log.info("this is time out");
        Thread.sleep(3000L);
        return ObjectResult.succeed(this.port);
    }

    public ObjectResult handleTout() {
        log.info("this is handle time out");
        return ObjectResult.fail(GlobalCodeMsgEnum.FAIL_TOUT);
    }

    @GetMapping(value = "/tbreak/{id}")
    public ObjectResult tBreak(@PathVariable("id")Integer id){
        log.info("this is t break");
        if(0 > id){
            throw new IllegalArgumentException("id must be positive number");
        }

        return ObjectResult.succeed(IdUtil.fastSimpleUUID());
    }

    @Value("${config.info}")
    private String info;
    @Value("${config.version}")
    private String version;

    @GetMapping("/config")
    public ObjectResult getRemoteConfig(){
        log.info("get remote config");
        return ObjectResult.succeed(this.version);
    }

    @Value("${config.refresh}")
    private String refresh;

    @GetMapping("/refresh")
    public ObjectResult refreshConfig(){
        log.info("refresh config");

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        return rest.postForObject(this.refresh,new HttpEntity<>(headers),ObjectResult.class);
    }


}
